package com.changdu.seatunnel.admin.config;

import java.util.List;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.changdu.seatunnel.admin.config.converts.StringOrMappingJackson2HttpMessageConverter;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
    	registry.addMapping("/**")
	    	.allowedOriginPatterns("**")
	    	.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD")
	    	.allowCredentials(true)
	    	.maxAge(3600 * 24 * 30)
	    	.allowedHeaders("*");
    }
	
	@Bean
	public FilterRegistrationBean<AccessTokenFilterFilter> serverDebugFilter() {
		FilterRegistrationBean<AccessTokenFilterFilter> registration = new FilterRegistrationBean<>();
		registration.setFilter(new AccessTokenFilterFilter());
		registration.addUrlPatterns("/api/*");
		registration.setName("accessTokenFilter");
		registration.setOrder(Integer.MIN_VALUE);
		return registration;
	}    

	/**
	 * allow return string result type
	 * @author wangxiaoliang
	 */
	@Configuration
	public class WebConfiguration implements WebMvcConfigurer {

	    @Override
		public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
	        converters.removeIf(httpMessageConverter -> httpMessageConverter.getClass() == StringHttpMessageConverter.class);
	        converters.add(0, new StringOrMappingJackson2HttpMessageConverter());
	    }
	    
	    @Override
	    public void addCorsMappings(CorsRegistry registry) {
	    	registry.addMapping("/**")
		    	.allowedOriginPatterns("**")
		    	.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD")
		    	.allowCredentials(true)
		    	.maxAge(3600 * 24 * 30)
		    	.allowedHeaders("*");
	    }
		
	}
	
}